<?php

class Home_AdminController extends Zend_Controller_Action
{
	private $table_name = 'adminstrators';
	
    public function editAction()
    {
        $registry = new Zend_Controller_Request_Http();
		$session = new Zend_Session_Namespace('User');
		
		$this->serveXHTML();
		
		// Check for logged in
    	if (!isset($session->company_id)) {
    		$this->_redirect('/index/index');
    	}
    	
    	$nav = new SwatNavBar();
    	$nav->title = 'Navigation Trail';
    	$nav->addEntry(new SwatNavBarEntry('Home', $registry->getBaseUrl().'/home'));
    	$nav->addEntry(new SwatNavBarEntry('Admin', $registry->getBaseUrl().'/home/admin'));
    	$nav->addEntry(new SwatNavBarEntry('Edit'));
    	$this->view->nav = $nav;
    	
    	if($session->saved === true){
    		$this->setNotice('Your information has been saved.');
    		unset($session->saved);
      	}
      	
    	$frame = new SwatFrame();
    	$frame->title = 'Edit Admin Profile';
    	$form = new SwatForm('form_edit');
    	$form->action = 'save';
    	
    	$this->connectDatabase();
    	$this->getMetaData();
    	
    	$this->parseForm($form);

    	$footer = new SwatFooterFormField();
    	$submit = new SwatButton();
    	$submit->title = 'Save Information';
    	
    	$footer->add($submit);
    	$form->add($footer);
    	$frame->add($form);
    	
    	$this->view->company = $this->companyData;
    	$this->view->form = $frame;
    	$this->view->baseUrl = $registry->getBaseUrl();
    	$this->view->time = (microtime(true) - Zend_Registry::get('startTime'));
    	
    }
    
    public function saveAction()
    {
		
		$session = new Zend_Session_Namespace('User');
		$front = Zend_Controller_Front::getInstance();
		
    	$this->connectDatabase();
    	$this->getMetaData();
    	
    	$db = $this->db;
    	
    	$set_keys = array();
    	$set_values = array();
    	
    	unset($this->data['company_id']);
    	foreach($this->metadata as $data_key => $data_value)
    	{	
    		if($data_value["field_value"] != $this->_getParam($data_key))
    		{
	    		$set_keys[] = $data_key.' = ?';
	    		$set_values[] = $this->_getParam($data_key);
	    	}
    	}
    	$set_values[] = $session->company_id;
    	if (count($set_keys) > 1) 
    	{
			$sql = 'UPDATE adminstrators SET '.implode(', ', $set_keys).' WHERE company_id = ?';
			//$stmt = $db->prepare($sql);
			//$stmt->execute($set_values);
		}
		
		$session->saved = true;
		
		//$this->_redirect('/home/admin/edit');
		
		$front->setParam('noViewRenderer', true);
    }
    
    public function setNotice($message) {
    	$this->view->notice = new SwatMessageDisplay('notice_message');
    	$this->view->notice->add( 
    		new SwatMessage($message,
      		SwatMessage::NOTIFICATION), 1);
    }
    
    public function connectDatabase()
    {
    	$config = Zend_Registry::get('config');
		
		$this->db = Zend_Db::factory($config->database->type, array(
		    'host'     => $config->database->host,
		    'username' => $config->database->username,
		    'password' => $config->database->password,
		    'dbname'   => $config->database->name
		));
    
    }
    
    public function getData()
    {
		$session = new Zend_Session_Namespace('User');
    	$db = $this->db;
		$select = $db->select()
			->from($this->table_name)
			->where('company_id = ?', intval($session->company_id));
		$stmt = $select->query();
		$this->data = $stmt->fetchAll();
		$this->data = $this->data[0];
    }
    
    public function getMetaData()
    {
  		$this->getData();
    	$db = $this->db;
		$select = $db->select()
			->from('metadata')
			->where('table_name = ?', $this->table_name)
			->order(array('field_order'));
		$stmt = $select->query();
		$this->metadata = $stmt->fetchAll();
  		$this->mergeMetadata();
    }
    
    public function mergeMetadata()
    {
    	$metadatas = array();
    	foreach($this->metadata as $metadata)
    	{
    		$metadata['field_value'] = $this->data[$metadata['field']];
    		$metadatas[$metadata['field']] = $metadata;
    	}    
    	$this->metadata = $metadatas;
    }
    
    public function serveXHTML()
    {
    	if(stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml"))
    	{
			header("Content-Type: application/xhtml+xml; charset=UTF-8");
		} 
		else 
		{
			header("Content-Type: text/html; charset=UTF-8");
		}
    }
    
    public function parseForm (&$form)
    {
        foreach($this->metadata as $metadata)
    	{
	    	if ($metadata['field_type'] == 'select')
	    	{
	    		$select = new SwatFlydown($metadata['field']);
	    		$options = explode(';', $metadata['field_data']);
	    		foreach($options as $option)
	    		{
	    			$select->addOption(new SwatOption($option, $option, 'text/xml'));
	    		}
		    	$select->value = $metadata['field_value'];
		    	$form->addWithField($select, $metadata['field_title']);
	    	}
	    	else
	    	{
	    		$input = new $metadata['field_type']($metadata['field']);
		    	$input->size = ($metadata['field_max'] == 0) ? 24 : $metadata['field_max'];
		    	$input->value = ($metadata['field_type'] != 'SwatPasswordEntry') ? $metadata['field_value'] : null;
		    	$form->addWithField($input, $metadata['field_title']);
	    	}
    	}
    }
}

?>
